package com.huluobo.day11_im.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.huluobo.day11_im.R;
import com.huluobo.day11_im.login.view.LoginActivity;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.uuzuche.lib_zxing.activity.CodeUtils;

public class MineFragment extends Fragment {

    private Button logout;
    private ImageView zxing_iv;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_mine, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        logout = view.findViewById(R.id.mine_logout);
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
            }
        });
        String username = String.format(getString(R.string.logout),
                EMClient.getInstance().getCurrentUser());
        logout.setText(username);

        zxing_iv = view.findViewById(R.id.zxing_iv);
        //生成二维码中心的图片
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                R.mipmap.ic_launcher);
        Bitmap image = CodeUtils.createImage(EMClient.getInstance().getCurrentUser(), 400, 400, bitmap);
        zxing_iv.setImageBitmap(image);
    }

    public void logout() {
        EMClient.getInstance().logout(true, new EMCallBack() {
            @Override
            public void onSuccess() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "退出登录成功", Toast.LENGTH_SHORT).show();
                    }
                });
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                getActivity().finish();
            }

            @Override
            public void onError(int code, String error) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "退出登录失败:" + error, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
}